const http = require("http");
const url = require("url");
const fs = require("fs");
const mysql = require("mysql");
const io = require("socket.io");
let db = mysql.createPool({
	connectionLimit:5,
	host:"localhost",
	user:'root',
	password:"lx1993225",
	database:"chat"
});
const server = http.createServer((req,res)=>{
	fs.readFile(`www${url.parse(req.url).pathname}`,(err,data)=>{
		if(err){
			res.writeHeader(404);
			res.write("not found")
		}else{
			res.write(data)
		}
	});
});
let aSock = [];
const wsSocket = io.listen(server);
wsSocket.on("connection",sock=>{
	aSock.push(sock);
	let current_name = ''
	let current_ID = 0;
	sock.on('reg',(user,pass)=>{
		if(!/^\w{6,32}$/.test(user)){
			sock.emit("reg_ret",1,'用户名不符合规范')
		}else if(!/^.{6,32}$/.test(pass)){
			sock.emit("reg_ret",1,'密码不符合规范')
		}else{
			db.query(`SELECT ID FROM user_table WHERE username='${user}'`,(err,data)=>{
				if(err){
					sock.emit("reg_ret",1,'数据库错误1')
				}else if(data.length!==0){
					sock.emit("reg_ret",1,'用户名已注册')
				}else{
					db.query(`INSERT INTO user_table (username,password,online) VALUES('${user}','${pass}',0)`,(err,data)=>{
						if(err){
							sock.emit("reg_ret",1,'数据库错误2')
						}else{
							sock.emit("reg_ret",0,'注册成功')
						}
					})
				}
			})
		}
	});
	//登陆
	sock.on('log',(user,pass)=>{
		if(!/^\w{6,32}$/.test(user)){
			sock.emit("log_ret",1,'用户名不符合规范')
		}else if(!/^.{6,32}$/.test(pass)){
			sock.emit("log_ret",1,'密码不符合规范')
		}else{
			db.query(`SELECT ID,password FROM user_table WHERE username='${user}'`,(err,data1)=>{
				if(err){
					sock.emit("log_ret",1,"数据库有问题")
				}else if(data1.length==0){
					sock.emit("log_ret",1,"查无此人")
				}else if(data1[0].password!=pass){
					sock.emit("log_ret",1,"用户名或密码错误")
				}else{
					db.query(`UPDATE user_table SET online=1 WHERE username='${user}'`,(err,data)=>{
						if(err){
							sock.emit("log_ret",1,"更新失败")
						}else{
							sock.emit("log_ret",0,"登陆成功")
							current_name = user;
							current_ID = data1[0].ID;
						}
					})
				}
			})
		}
	});
	//发言
	sock.on('msg',txt=>{
		if(!txt){
			sock.emit("msg_ret",1,'消息文本不能为空')
		}else{
			aSock.forEach(item=>{
				//自己发的不给发送
				if(item==sock) return;
				//吧别人得内容广播出去
				item.emit("msg",current_name,txt)
			});
			sock.emit("msg_ret",0,'发送成功')
		}
	})
	//离线
	sock.on("disconnect",()=>{
		db.query(`UPDATE user_table SET online=0 WHERE username = '${current_name}'`,(err)=>{
			if(err){
				console.log('离线'+ err);
			};
			current_name = '';
			current_ID = 0;
			aSock = aSock.filter(item=>item!=sock)
		})
	})
})
server.listen(8080)